package strcy.cn.market.utils;


import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Component
@Slf4j
public class QiNiuOSSUtil {

    @Autowired
    private QiNiuOSSProperties qiNiuOSSProperties;


    public String upload(MultipartFile file) throws IOException {

        String accessKey = qiNiuOSSProperties.getAccessKey();
        String secretKey = qiNiuOSSProperties.getSecretKey();
        String bucket = qiNiuOSSProperties.getBucket();
        String domain = qiNiuOSSProperties.getDomain();

        // 获取文件输入流
        try (InputStream inputStream = file.getInputStream()) {
            // 避免文件覆盖
            String originalFilename = file.getOriginalFilename();
            String fileName = "market/" + UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

            // 构造一个带指定 Region 对象的配置类
            Configuration cfg = new Configuration(Region.autoRegion());
            // 其他参数参考类注释
            cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;

            // 创建上传对象
            UploadManager uploadManager = new UploadManager(cfg);

            // 身份认证
            Auth auth = Auth.create(accessKey, secretKey);

            // 指定覆盖上传
            String upToken = auth.uploadToken(bucket);

            try {
                // 上传
                Response response = uploadManager.put(inputStream, fileName, upToken, null, null);
                // 文件访问路径
                String url = domain + fileName;
                log.info("File uploaded successfully: {}", url);
                return url;
            } catch (QiniuException e) {
                // 处理上传失败的情况
                log.error("Failed to upload file: {}", e.getMessage());
                throw new IOException("Failed to upload file to Qiniu OSS", e);
            }
        } catch (IOException e) {
            // 处理文件读取失败的情况
            log.error("Failed to read file: {}", e.getMessage());
            throw e;
        }
    }
}
